package com.wuyi.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wuyi.mapper.ResourceCustomerMapper;
import com.wuyi.mapper.ResourceMapper;
import com.wuyi.pojo.Resource;
import com.wuyi.pojo.bo.CenterResDelBO;
import com.wuyi.pojo.bo.ResourceBO;
import com.wuyi.pojo.bo.ResourcesBO;
import com.wuyi.service.FileUploadService;
import com.wuyi.service.ResourceService;
import com.zc.utils.JSONResult;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

/**
 * @author 曾川
 * @version 1.0.0
 * @ClassName ResourceServiceImpl.java
 * @Description 资源模块实现类
 * @createTime 2021年10月19日 13:24:00
 */
@Service
public class ResourceServiceImpl implements ResourceService {

    public final static Logger logger = LoggerFactory.getLogger(ResourceServiceImpl.class);

    @Autowired
    private ResourceMapper resourceMapper;

    @Autowired
    private ResourceCustomerMapper resourceCustomerMapper;

    @Autowired
    private FileUploadService fileUploadService;


    /**
     * 首页查询10条信息，先按资源优秀查询，再按时间
     * @return list
     */
    @Transactional( propagation = Propagation.SUPPORTS)
    @Override
    public List<Resource> list() {

        List<Resource> list = resourceCustomerMapper.queryResourceList();
        return list;
    }

    /**
     * 上传资源
     * @param resourcesBO
     * @return
     */
    @Transactional( propagation = Propagation.REQUIRED)
    @Override
    public JSONResult addResource(ResourcesBO resourcesBO) throws IOException {

        MultipartFile coverImg = resourcesBO.getResourceImage();
        MultipartFile[] files = resourcesBO.getResourceUrl();
        //存到数据库的封面图片路径
        String imgPath = "";
        //存到数据库的文件路径
        int i = 0;
        String[] filePaths = new String[files.length];
        //开始上传图片文件
        if (null != coverImg) {
//            imgPath = fileUploadService.upload(coverImg, resourcesBO.getResourceUid(), "resource");
            imgPath = fileUploadService.upload2(coverImg, resourcesBO.getResourceUid(), "resource");
        }

        //开始上传文件
        if (files.length > 0 && null != files) {
            for (MultipartFile file : files) {
//                String filePath = fileUploadService.upload(file, resourcesBO.getResourceUid(), "resource");
                String filePath = fileUploadService.upload2(file, resourcesBO.getResourceUid(), "resource");

                filePaths[i++] = filePath;
            }
        }

        //调用service插入数据
        StringBuilder sb = new StringBuilder();
        for (String f : filePaths) {
            sb.append(f).append(",");
            logger.info("------------资源文件路径" + f);
        }

        logger.info("fileFinalPath--------------:"+ sb.substring(0,sb.length() - 1));
        String fileFinalPath = sb.substring(0,sb.length() - 1);

        Resource resource = new Resource();
        resource.setResourceName(resourcesBO.getResourceName());
        resource.setResourceUid(resourcesBO.getResourceUid());
        resource.setResourceCid(resourcesBO.getResourceCid());
        resource.setResourceDesc(resourcesBO.getResourceDesc());
        resource.setResourceImage(imgPath);
        resource.setResourceUrl(fileFinalPath);
        resource.setResourceTime(new Date());
        resource.setCreateTime(new Date());
        resource.setUpdateTime(new Date());

        resourceMapper.insert(resource);


        return JSONResult.ok(resource);
    }

    /*@Transactional( propagation = Propagation.REQUIRED)
    @Override
    public void addRes(String resourceName,
                       Integer resourceCid,
                       String resourceUid,
                       String resourceDesc,
                       String coverPath,
                       String filePath) {

        Resource resource = new Resource();
        resource.setResourceName(resourceName);
        resource.setResourceCid(resourceCid);
        resource.setResourceUid(resourceUid);
        resource.setResourceDesc(resourceDesc);
        resource.setResourceImage(coverPath);
        resource.setResourceUrl(filePath);
        resource.setResourceTime(new Date());
        resource.setCreateTime(new Date());
        resource.setUpdateTime(new Date());
        resourceMapper.insert(resource);
    }*/


    /**
     * @param resourceBO
     */
    @Override
    public List<Resource> queryResInfo(ResourceBO resourceBO) {



        return null;
    }

    /**
     * 下载资源
     *
     * @param path
     * @param response
     */
    @Override
    public void download(String path, HttpServletResponse response) {
        try {
            // path是指想要下载的文件的路径
            File file = new File(path);
            logger.info(file.getPath());
            // 获取文件名
            String filename = file.getName();
            // 获取文件后缀名
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
            logger.info("文件后缀名：" + ext);

            // 将文件写入输入流
            FileInputStream fileInputStream = new FileInputStream(file);
            InputStream fis = new BufferedInputStream(fileInputStream);
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();

            // 清空response
            response.reset();
            // 设置response的Header
            response.setCharacterEncoding("UTF-8");
            //Content-Disposition的作用：告知浏览器以何种方式显示响应返回的文件，用浏览器打开还是以附件的形式下载到本地保存
            //attachment表示以附件方式下载 inline表示在线打开 "Content-Disposition: inline; filename=文件名.mp3"
            // filename表示文件的默认名称，因为网络传输只支持URL编码的相关支付，因此需要将文件名URL编码后进行传输,前端收到后需要反编码才能获取到真正的名称
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
            // 告知浏览器文件的大小
            response.addHeader("Content-Length", "" + file.length());
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            outputStream.write(buffer);
            outputStream.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    @Transactional( propagation = Propagation.SUPPORTS)
    @Override
    public PageInfo queryResList(String userName, String resourceName,
                                       Integer categoryId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        Example example = new Example(Resource.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("resourceUid", userName);
        criteria.andEqualTo("resourceCid", categoryId);
        if (StringUtils.isNotBlank(resourceName)) {
            criteria.andLike("resourceName" , "%" + resourceName + "%");
        }
        example.orderBy("createTime").desc();
        List<Resource> resourceList = resourceMapper.selectByExample(example);
        PageInfo pageInfo = new PageInfo<>(resourceList);
        pageInfo.setList(resourceList);

        return pageInfo;
    }

    @Transactional( propagation = Propagation.REQUIRED)
    @Override
    public JSONResult delRes(CenterResDelBO resDelBO) {

        Resource resource = new Resource();
        resource.setResourceId(resDelBO.getResourceId());
        resource.setResourceUid(resDelBO.getUserName());

        int i = resourceMapper.deleteByPrimaryKey(resource);
        if (i != 1) {
            return JSONResult.errorMsg("删除资源失败");
        }

        return JSONResult.ok("删除成功");
    }
}
